package com.chcit.mobile.app.exception;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import com.elvishew.xlog.XLog;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.base.app.Quick;

import java.net.ConnectException;

import androidx.appcompat.app.AppCompatActivity;


public class BaseUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

	// CrashHandler实例

	private static final class BaseUncaughtExceptionHandlerHolder {
		private final static BaseUncaughtExceptionHandler INSTANCE;

        static {
            INSTANCE = new BaseUncaughtExceptionHandler();
        }
    }
	// 用来存储设备信息和异常信息
    private final Context mContext  = Quick.<AppCompatActivity>getConfiguration(ConfigKeys.APPLICATION_CONTEXT);
	private String msg = "";
	//private static boolean onFlag = false;//是否退出应用
	/** 保证只有一个CrashHandler实例 */
	private BaseUncaughtExceptionHandler() {

	}

	public static BaseUncaughtExceptionHandler getInstance() {
		return BaseUncaughtExceptionHandlerHolder.INSTANCE;
	}
	
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) &&  Thread.getDefaultUncaughtExceptionHandler() != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			Thread.getDefaultUncaughtExceptionHandler().uncaughtException(thread, ex);
		}else {
			showDialog();
		} 

	}

	/**
	 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
	 * 
	 * @param
	 * @return true:如果处理了该异常信息;否则返回false.
	 */
	private boolean handleException(Throwable ex) {
		if (ex == null) {
			return false;
		}
		if (ex instanceof BaseException) {
			BaseException be = (BaseException) ex;
			msg = be.getcodeMsg().getMsg();
		} else if (ex instanceof NullPointerException) {
			msg = "空指针异常！";

		} else if (ex instanceof ConnectException) {
			// ConnectException ce = (ConnectException)ex;
			msg = "网络异常";
		} else if (ex instanceof Exception) {
			Exception ce = (Exception) ex;
			msg = ce.getMessage();
		}
		// 收集设备参数信息
		XLog.e("系统错误",ex);
		return true;

	}



	private void showDialog() {

		Intent intent = new Intent(Quick.getApplicationContext(), ErrorShowActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
		Quick.getApplicationContext().startActivity(intent);
		System.exit(0);// 关闭已奔溃的app进程
       /* MaterialDialog buder = new MaterialDialog.Builder(mContext)
                .title("温馨提示")
                .content(msg)
                .positiveText("退出")
                .negativeText("重启")
                //点击事件添加 方式1
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {
                        AppManager.getAppManager().AppExit(Quick.getApplicationContext());
                        // Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                    } else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        AppUtils.relaunchApp();
                    }
                    dialog.dismiss();
                }).build();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
				Objects.requireNonNull(buder.getWindow()).setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
		} else {
			//Android6.0以下，不用动态声明权限
			Objects.requireNonNull(buder.getWindow()).setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		}

		*//*if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
			Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		}else{
			Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);

		}*//*
		buder.setCanceledOnTouchOutside(false);// 设置点击屏幕其他地方，dialog不消失
		buder.setCancelable(false);// 设置点击返回键和HOme键，dialog不消失
		buder.show();*/
	}
	
	public Class<?> getTopActivity() {
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        String className = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        Class<?> cls = null;
        try {  
            cls = Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  
        }  
        return cls;  
    }


}
